package org.example.authentication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.authentication.mapper.SysUserMapper;
import org.example.authentication.pojo.SysPermissions;
import org.example.authentication.pojo.SysRole;
import org.example.authentication.pojo.SysUser;
import org.example.authentication.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser listRolePermByName(String username) {
        SysUser sysUser = this.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (null == sysUser) {
            return null;
        }
        Set<String> roles = this.baseMapper.listRolesByName(username);
        Set<SysRole> sysRoles = new HashSet<>();
        for (String role : roles) {
            Set<SysPermissions> sysPermissions = this.baseMapper.listPermsByRoleName(role);
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(role);
            sysRole.setPermissions(sysPermissions);
            sysRoles.add(sysRole);
        }
        sysUser.setRoles(sysRoles);
        return sysUser;
    }

    @Override
    public SysUser getUser(String username) {
        return sysUserMapper.getUser(username);
    }
}
